package otlex

import (
	"crypto/tls"
	"crypto/x509"
	"os"
)

type ProtocolType = string

const (
	Grpc   ProtocolType = "grpc"
	Http   ProtocolType = "http"
	Stdout ProtocolType = "stdout"
)

type TLS struct {
	Enable bool   `json:"enable" toml:"enable"`
	Mode   string `json:"mode" toml:"mode"`
	CaCert string `json:"ca_cert" toml:"ca_cert"`

	Cert string `json:"cert" toml:"cert"`
	Key  string `json:"key" toml:"key"`
}

func (r TLS) IsEnable() bool {
	return r.Enable
}

func (r TLS) Tls() *tls.Config {
	caCert, err := os.ReadFile(r.CaCert)
	if err != nil {
		panic(err)
	}

	caCertPool := x509.NewCertPool()
	if ok := caCertPool.AppendCertsFromPEM(caCert); !ok {
		panic("Errorf: CA file must be in PEM format")
	}
	// Loads client certificate files
	cert, err := tls.LoadX509KeyPair(r.Cert, r.Key)
	if err != nil {
		panic(err)
	}
	// Instantiates a ExporterConfig instance
	tlsConfig := tls.Config{
		RootCAs:      caCertPool,
		Certificates: []tls.Certificate{cert},
	}

	return &tlsConfig
}
